package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter(filterName = "PersonagePort",value = {"/personage/*"})
public class PersonagePort implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        if(validationCookie(req,"ROOT","SID")){
            chain.doFilter(req,resp);
            return;
        }

        if(!validationCookie(req,"ID","SID")){
            return;
        }

        String id=req.getParameter("id");
        if(((HttpServletRequest) req).getSession().getAttribute(id)==null){
            return;
        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    //判断是否通过cookie验证，若是则返回true，若否则返回false
    public static boolean validationCookie(ServletRequest req,String name,String val){
        try {
            Map<String,String> map=new HashMap<>();

            //先把cookie映射成哈希表
            Cookie[] cookies=((HttpServletRequest)req).getCookies();

            //先找到对应的cookie
            for(int i=0;i<cookies.length;i++) {
                map.put(cookies[i].getName(),cookies[i].getValue());
            }

            String id=map.get(name);
            String sid=map.get(val);

            if(sid.equals(((HttpServletRequest) req).getSession().getAttribute(id))){
                return true;
            }
        }catch (Exception ex){
            return false;
        }

        return false;
    }
}
